import { Button, Drawer, Form, Input, Spin } from "antd";
import { useForm } from "antd/lib/form/Form";
import { ErrorBox } from "components/lib";
import { UserSelect } from "components/user-select";
import { useEffect } from "react";
import { useProjectModal, useProjectQueryKey } from "screens/project-list/util";
import { useAddProject, useEditProject } from "utils/project";

export const ProjectModal = () => {
  const { projectModalOpen, close, editingProject, startEdit, isLoading } = useProjectModal();
  const [form] = useForm();

  const useMutateProject = editingProject ? useEditProject : useAddProject
  const { mutateAsync, isLoading: mutateLoading, error } = useMutateProject(useProjectQueryKey())

  const onFinish = (values: any) => {
    mutateAsync({ ...editingProject, ...values }).then(() => {
      form.resetFields()
      close()
    })
  }

  const onClose = () => {
    form.resetFields()
    close()
  }

  useEffect(() => {
    form.setFieldsValue(editingProject)
  }, [editingProject, form])

  const title = editingProject ? '编辑项目' : '创建项目'
  return (
    <Drawer
      forceRender={true}
      closable={true}
      onClose={onClose}
      visible={projectModalOpen}
      width={'100%'}
    >
      {
        isLoading ?
          (
            <Spin size={'large'} />
          ) :
          (
            <>
              <h1>{title}</h1>
              <ErrorBox error={error} />
              <Form form={form} layout={'vertical'} style={{ width: '40rem' }} onFinish={onFinish}>
                <Form.Item label={'名称'} name={'name'} rules={[{ required: true, message: '请输入名称' }]}>
                  <Input placeholder={'请输入名称'} />
                </Form.Item>
                <Form.Item label={'部门'} name={'organization'} rules={[{ required: true, message: '请输入部门名称' }]}>
                  <Input placeholder={'请输入部门名称'} />
                </Form.Item>
                <Form.Item label={'负责人'} name={'personId'} rules={[{ required: true, message: '请选择负责人' }]}>
                  <UserSelect defaultOptionName={'负责人'} />
                </Form.Item>
                <Form.Item style={{ textAlign: "right" }}>
                  <Button loading={mutateLoading} type={'primary'} htmlType={'submit'}>提交</Button>
                </Form.Item>
              </Form>
            </>
          )
      }

    </Drawer>
  );
};
